package com.dnjn.happiness.biz.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dnjn.happiness.biz.domain.Checkup;
import com.dnjn.happiness.biz.mapper.CheckupMapper;
import com.dnjn.happiness.biz.service.ICheckupService;
import com.dnjn.happiness.common.core.exception.ServiceException;
import com.dnjn.happiness.common.core.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 体检Service业务层处理
 *
 * @author happiness
 * @date 2024-03-27
 */
@Service
public class CheckupServiceImpl extends ServiceImpl<CheckupMapper, Checkup> implements ICheckupService {

    @Override
    public String importData(List<Checkup> list) {
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Checkup dto : list) {
            try {
                if (StringUtils.isNotEmpty(dto.getAge())) {
                    dto.setAge(StringUtils.removeEnd(dto.getAge(), "岁"));
                }
                //根据体检编号判断是否已经存在，存在就更新。
                if (StringUtils.isNotEmpty(dto.getCheckupRef())) {
                    Checkup c = baseMapper.selectCheckupByRef(dto.getCheckupRef());
                    if (Objects.isNull(c)) {
                        baseMapper.insert(dto);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、体检编号 " + dto.getCheckupRef() + " 体检记录导入成功");
                    } else {
                        baseMapper.updateByRef(dto);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、体检编号 " + dto.getCheckupRef() + " 体检记录更新成功");
                    }
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、用户" + dto.getNickName() + "体检编号为空！ " + " 体检记录导入失败：");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、体检编号 " + dto.getCheckupRef() + " 体检记录导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "共" + successNum + "条数据导入成功！共 " + failureNum + " 条数据格式不正确,导入失败，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString() + failureMsg.toString();
    }

    @Override
    public Page<Checkup> getPage(Page page, Checkup checkup) {
        return baseMapper.getPage(page, checkup);
    }
}
